using UnityEngine;

[ExecuteAlways]                 // 关键：编辑器和运行时都执行
[DisallowMultipleComponent]
public class TintWithMPB : MonoBehaviour
{
    [SerializeField] Color tint = Color.green;
    [SerializeField] bool enableTint = true;

    static readonly int BaseColorID = Shader.PropertyToID("_BaseColor"); // URP Lit
    static readonly int ColorID     = Shader.PropertyToID("_Color");     // 其它/旧着色器

    Renderer r;
    MaterialPropertyBlock mpb;

    void OnEnable()
    {
        r   = GetComponent<Renderer>();
        mpb = mpb ?? new MaterialPropertyBlock();
        Apply();                    // 进入编辑器/场景时就应用
    }

    void OnDisable()
    {
        // 退出/禁用时清理（编辑器下不留脏状态）
        if (!Application.isPlaying) Clear();
    }

    void OnValidate()
    {
        // 在 Inspector 改值时实时刷新
        if (!r) r = GetComponent<Renderer>();
        mpb = mpb ?? new MaterialPropertyBlock();
        Apply();
    }

    [ContextMenu("Apply Tint")]
    public void Apply()
    {
        if (!r || !r.sharedMaterial) return;

        r.GetPropertyBlock(mpb);
        if (enableTint)
        {
            var mat = r.sharedMaterial;
            if (mat.HasProperty(BaseColorID)) mpb.SetColor(BaseColorID, tint);
            else if (mat.HasProperty(ColorID)) mpb.SetColor(ColorID, tint);
        }
        else
        {
            mpb.Clear();
        }
        r.SetPropertyBlock(mpb);
    }

    [ContextMenu("Clear Tint")]
    public void Clear()
    {
        if (r) r.SetPropertyBlock(null);
    }
}